<template>
    <div>
        <button class="loginBtn" open-type="getUserInfo" @getuserinfo="login" v-if="!logined">授权登录</button>
        <div class="container" v-else>
            <div class="userinfo">
                <img :src="userinfo.avatarUrl" alt="">
                <p>{{userinfo.nickName}}</p>
            </div>
            <year-progress></year-progress>
            <button class="btn" @click="scanCode">添加图书</button>
        </div>
    </div>
</template>

<script>
import qcloud from "wafer2-client-sdk";
import config from "@/config";
import {showSuccess, post, showModal} from "@/util"
import YearProgress from "@/components/YearProgress/YearProgress"
export default {
  components:{
    YearProgress
  },
  created() {
      let userinfo = wx.getStorageSync('userinfo')
      if(userinfo){
        this.logined = true
        this.userinfo = userinfo
        showSuccess('登录成功')
      }
  },
  data () {
      return {
         logined: false,
         userinfo: {}
      }
  },
  methods: {
    async addBook(isbn) {
      const res = await post('/weapp/addbook',{
        openid:this.userinfo.openId,
        isbn:isbn
      })
			showModal('添加成功',`${res.title}添加成功`)
    },
    scanCode() {
        wx.scanCode({
            success: (res) => {
              	const result = res.result
                if(result){
                    this.addBook(result)
                }
            },
            fail (res) {
                // 扫描不出二维码的时候
                console.log(res)
                showModal('失败','扫描失败')
            }
        })
    },
    login(login) {
      let that = this
    //   let user = wx.getStorageSync("userinfo");
        qcloud.setLoginUrl(config.loginUrl);
        qcloud.login({
          success: function(userInfo) {
            wx.setStorageSync('userinfo',userInfo)
            showSuccess('登录成功')
            that.logined = true
            that.userinfo = userInfo
          },
          fail: function(err) {
            console.log("登录失败", err);
          }
        })

    }
  }
};
</script>

<style lang="stylus" scoped>
    @import '~style/varibles.styl'
    .loginBtn
        margin-top 100rpx
        width 400rpx
        height 60rpx
        line-height 60rpx
        font-size 24rpx
    .container
        padding 0 30rpx
        .userinfo
            margin-top 100rpx
            text-align center
            img
                width 150rpx
                height 150rpx
                margin 20rpx
                border-radius 50%
</style>

